package com.persistence;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Query;


import com.domain.AppUser;

public class UserAccessObject extends DataAccessObject<AppUser>{
	
	@Override
	public ArrayList<AppUser> getObjects() {
		this.getPersistenceManagerInstance();
		ArrayList<AppUser> usersList = getUsersList();
		this.closePersistenceManager();
		return usersList;
	}

	@Override
	public AppUser getObject(String searchValue) {
		getPersistenceManagerInstance();
		AppUser searchedUser = getUser(searchValue);
		closePersistenceManager();
		return searchedUser;
	}
	
	@SuppressWarnings("unchecked")
	private AppUser getUser(String searchValue){
		AppUser user = null;
		Query query = persistenceManager.newQuery(AppUser.class,"userName == '" + searchValue + "'");
		List<AppUser> results = (List<AppUser>)query.execute();
		if(results.size() > 0){
			user = results.get(0);
		}
		query.closeAll();
		return user;
	}
	
	@SuppressWarnings("unchecked")
	private ArrayList<AppUser> getUsersList(){
		ArrayList<AppUser> usersList = new ArrayList<AppUser>();
		Query query = persistenceManager.newQuery(AppUser.class);
		List<AppUser> list = (List<AppUser>)query.execute();
		for(AppUser user : list){
			usersList.add(user);
		}
		query.closeAll();
		return usersList;
	}
}
